#+TITLE: Emacs configuration

Inspired by [[https://github.com/hrs/dotfiles/tree/master/emacs.d][hrs]] and [[https://github.com/pierre-lecocq/emacs.d/tree/literal][pierre-lecocq]] org configs

* General
** Package management

   Setup repositories for package and auto download use-package if it's missing. 
   #+BEGIN_SRC emacs-lisp
     (require 'package)

     (setq package-archives
           '(("melpa-stable" . "http://stable.melpa.org/packages/")
             ("melpa"        . "http://melpa.org/packages/")
             ("gnu"          . "http://elpa.gnu.org/packages/")
             ("org"          . "http://orgmode.org/elpa/")))

     (package-initialize)

     (when (not package-archive-contents)
       (package-refresh-contents))

     (setq package-enable-at-startup nil)

     ;; Pin melpa-stable for packages not under use-package control, i.e
     ;; dependencies and use-package itself.
     (setq package-pinned-packages
           '((use-package . "melpa-stable")
             ;; Deps
             (async       . "melpa-stable")
             (bind-key    . "melpa-stable")
             (dash        . "melpa-stable")
             (diminish    . "melpa-stable")
             (epl         . "melpa-stable")
             (git-commit  . "melpa-stable")
             (magit-popup . "melpa-stable")
             (pkg-info    . "melpa-stable")
             (popup       . "melpa-stable")
             (s           . "melpa-stable")
             (with-editor . "melpa-stable")))

     (unless (package-installed-p 'use-package)
       (package-install 'use-package))
   #+END_SRC

   Let use-package handle all the packages I use
   #+BEGIN_SRC emacs-lisp
     (eval-when-compile
       (require 'use-package))
     (require 'diminish)                ;; if you use :diminish
     (require 'bind-key)                ;; if you use any :bind variant
   #+END_SRC

   Install missing packages.
   #+BEGIN_SRC emacs-lisp
     (setq use-package-always-ensure t)
   #+END_SRC
** Customizations
   Set emacs to save the customizations in a separate file to avoid
   having them in the git repo.
   #+BEGIN_SRC emacs-lisp
     (setq custom-file "~/.emacs.d/.custom.el")
     (when (file-exists-p custom-file) (load custom-file))
   #+END_SRC
** Custom plugins
*** Dotemacs
    Export a variable if I'm at work or not.
    #+BEGIN_SRC emacs-lisp
      (use-package dotemacs
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
** UI
*** Maximize work area
   Disable the menu, tool and scroll bar since they just take up
   space.
   #+BEGIN_SRC emacs-lisp
     (menu-bar-mode 0)
     (tool-bar-mode 0)
     (when (window-system) (scroll-bar-mode 0))
   #+END_SRC
*** Font
    Set font and font size
    #+BEGIN_SRC emacs-lisp
      (set-frame-font "Hack-9" nil t)
    #+END_SRC
*** Column number
   Show column number in the info bar
   #+BEGIN_SRC emacs-lisp
     (column-number-mode 1)
   #+END_SRC
** Behaviour
   Changing the default emacs behavior to better suite me.
   #+BEGIN_SRC emacs-lisp
     (setq-default
	electric-indent-mode nil        ;; Disable electric-indent-mode, C-j is used for that.
	load-prefer-newer t             ;; Avoid loading outdated byte code files.
	auto-hscroll-mode 'current-line ;; Activate single-line horizontal scrolling mode (emacs-26 and up).
	inhibit-splash-screen t         ;; Dismiss the startup screen.
	initial-scratch-message ""      ;; Empty scratch buffer.
	calendar-week-start-day 1)      ;; Week starts on Monday.
     (show-paren-mode 1)                ;; Highlight matching brackets.
   #+END_SRC
** Backup/autosave
   One annoying thing with emacs is it that it leaves backup files all
   over the place.  Fixing that by dumping all backup/autosave files
   in to one directory.
   #+BEGIN_SRC emacs-lisp
     (defvar backup-dir (expand-file-name "~/.emacs.d/backup/"))
     (defvar autosave-dir (expand-file-name "~/.emacs.d/autosave/"))
     (setq backup-directory-alist (list (cons ".*" backup-dir))
	   auto-save-list-file-prefix autosave-dir
	   auto-save-file-name-transforms `((".*" ,autosave-dir t)))
   #+END_SRC
** Theme
   Point emacs to where it can find the sunburst theme. Depending on
   if emacs is started in a shell or not load the correct theme.
   #+BEGIN_SRC emacs-lisp
     (add-to-list 'custom-theme-load-path "~/.emacs.d/themes/sunburst-theme")
     (load-theme `sunburst t)
   #+END_SRC
** Path
   #+BEGIN_SRC emacs-lisp
     (add-to-list 'exec-path (expand-file-name "~/bin"))
   #+END_SRC
* Packages
** Code
*** Autocomplete
   Packages that helps speed up coding, i.e. auto complete, boiler plates etc 
**** Auto complete
     Init auto-complete to use the default settings. Except auto
     complete words when pressing tab but disable it for enter.

     Disable autocomplete when typing // comments in c++.

     For the c-family (c++, c and c#) 
     ac-omni-completion-sources is made buffer local so you need to add
     it to a mode hook to activate on whatever buffer you want to use it
     with.  This example uses C mode (as you probably surmised).
     
     auto-complete.el expects ac-omni-completion-sources to be a list of
     cons cells where each cell's car is a regex that describes the
     syntactical bits you want AutoComplete to be aware of. The cdr of
     each cell is the source that will supply the completion data.  The
     following tells autocomplete to begin completion when you type in a
     . or a ->

     Enable autocomplete for arduino and gmake's makefile since they're
     not on by default.
     
     Note don't put the keybindings under :bind then this will not be
     loaded.
     #+BEGIN_SRC emacs-lisp
       (use-package auto-complete
         :config
         ;; :disabled t
         (ac-config-default)
         (define-key ac-completing-map "\t" 'ac-expand)
         (define-key ac-completing-map "\r" nil)

         ;; Ignore c++ comments
         (add-hook 'c++-mode-hook
                   (lambda ()
                     (make-local-variable 'ac-ignores)
                     (add-to-list 'ac-ignores "//")))
         ;; C-common: Start auto complete on . or ->
         (add-hook 'c-mode-common-hook 
                   '(lambda ()
                      (add-to-list 'ac-omni-completion-sources
                                   (cons "\\." '(ac-source-semantic)))
                      (add-to-list 'ac-omni-completion-sources
                                   (cons "->" '(ac-source-semantic)))
                      ))
         ;; Enable ac for gmake and arduino
         (add-to-list 'ac-modes 'makefile-gmake-mode)
         (add-to-list 'ac-modes 'arduino-mode)
         (use-package auto-complete-rst
           :pin melpa)
         ;; Messes with the navigation at work
         (use-package ac-rtags
           :disabled t
           :bind
           ("C-." . ac-complete-rtags)
           :config
           (ac-rtags-init)
           :pin melpa-stable)
         :pin melpa-stable)


     #+END_SRC
**** Company (disabled)

     Has some really nice features, but it's just too slow
     (company-clang that is).

     #+BEGIN_SRC emacs-lisp
       (use-package company
         :bind (("C-<tab>" . company-complete)
                ("C-n" . company-select-next)
                ("C-p" . company-select-previous))
         :disabled t
         :init
         ;; C++/C auto-complete
         (use-package irony
           :config
           (add-hook 'c++-mode-hook 'irony-mode)
           (add-hook 'c-mode-hook 'irony-mode)
           (add-hook 'irony-mode-hook 'irony-cdb-autosetup-compile-options)
           :pin melpa-stable)
         
         (use-package company-irony
           :config
           (add-to-list 'company-backends 'company-irony)
           :pin melpa-stable)

         ;; Shell autocomplete
         (use-package company-shell
           :config
           :pin melpa-stable)
         
         :config
         ;; List what modes to use company in.
         (add-hook 'c++-mode-hook 'company-mode)
         (add-hook 'c-mode-hook 'company-mode)
         (add-hook 'emacs-lisp-mode-hook 'company-mode)
         (add-hook 'shell-script-mode-hook 'company-mode)

         (setq company-idle-delay 0)
         (setq company-minimum-prefix-length 3)
         :pin melpa-stable)
     #+END_SRC
**** Yasnippet
     Enable yasnippet
     #+BEGIN_SRC emacs-lisp
       (use-package yasnippet 
       	 :config
       	 (yas-global-mode 1)
       	 (setq yas-indent-line nil)
       	 :pin melpa-stable)
     #+END_SRC
**** Semantic (disabled)
     NOTE: Notice a lot of lag when having this enabled for large
     files. Freezes every few seconds when editing etc.
     
     Keybindings for semantic mode. Semantic-ia-fast-jump works a lot
     better than the one assigned to "C-c , j"
     (semantic-complete-jump-local).

     And enable semantic for the C family.
     #+BEGIN_SRC emacs-lisp
       (use-package semantic
         :disabled t
         :bind (("M-," . semantic-ia-fast-jump)
                ("M-*" . pop-global-mark)
                ("C-c , i" . semantic-ia-show-summary)
                ("C-c , c" . semantic-ia-describe-class))
         :config
         (add-hook 'c-mode-common-hook 'semantic-mode))
     #+END_SRC
*** Lint
   Packages that helps inspecting code, report errors etc.
**** Flycheck
     Enable flycheck globably.

     Disable clang check, gcc check works better.
     #+BEGIN_SRC emacs-lisp
       (use-package flycheck
         :config
         (add-hook 'after-init-hook #'global-flycheck-mode)
         ;; Current version of rst-sphinx for flycheck disabling it
         (add-to-list 'auto-mode-alist '("\\.rst\\'" .
                                         (lambda () (rst-mode) (flycheck-mode -1)))) 
         :pin melpa-stable)

     #+END_SRC
     Tell emacs it's safe to change these in a .dir-locals.el file.
     #+BEGIN_SRC emacs-lisp
       (put 'flycheck-c/c++-gcc-executable 'safe-local-variable #'stringp) 
       (put 'flycheck-gcc-language-standard 'safe-local-variable #'stringp) 
       (put 'flycheck-gcc-include-path 'safe-local-variable #'listp) 
       (put 'flycheck-gcc-includes 'safe-local-variable #'listp) 
       (put 'flycheck-gcc-warnings 'safe-local-variable #'listp) 
       (put 'flycheck-gcc-definitions 'safe-local-variable #'listp) 
       (put 'flycheck-gcc-args 'safe-local-variable #'listp) 

       (put 'flycheck-c/c++-clang-executable 'safe-local-variable #'stringp) 
       (put 'flycheck-clang-language-standard 'safe-local-variable #'stringp) 
       (put 'flycheck-clang-include-path 'safe-local-variable #'listp) 
       (put 'flycheck-clang-includes 'safe-local-variable #'listp) 
       (put 'flycheck-clang-warnings 'safe-local-variable #'listp) 
       (put 'flycheck-clang-definitions 'safe-local-variable #'listp) 
       (put 'flycheck-clang-args 'safe-local-variable #'listp) 

       (put 'flycheck-checkers 'safe-local-variable #'listp)
     #+END_SRC
**** Demangle (Disabled)
     #+BEGIN_SRC emacs-lisp
       (use-package demangle-mode
       	 :disabled t
       	 :pin melpa-stable)
     #+END_SRC
*** Navigation
   Packages for navigating code.
**** GTags (Disabled)
     Key bindings for finding tag, reference and usage of symbol.

     Cycling gtag results ([[https://www.emacswiki.org/emacs/CyclingGTagsResult][source]])
     #+BEGIN_SRC emacs-lisp
       (use-package ggtags
       	 :disabled t
       	 :bind (("M-." . gtags-find-tag) ;; Finds tag
               	("C-M-." . gtags-find-rtag)   ;; Find all references of tag
               	("C-M-," . gtags-find-symbol)) ;; Find all usages of symbol.
       	 :config 
       	 (defun ww-next-gtag ()
               "Find next matching tag, for GTAGS."
               (interactive)
               (let ((latest-gtags-buffer
                      (car (delq nil  (mapcar (lambda (x) (and (string-match "GTAGS SELECT" (buffer-name x)) (buffer-name x)) )
                                              (buffer-list)) ))))
               	 (cond (latest-gtags-buffer
                       	(switch-to-buffer latest-gtags-buffer)
                       	(forward-line)
                       	(gtags-select-it nil))
                       )))
       	 :pin melpa-stable)

     #+END_SRC
**** RTags (Disabled)
     
     Key bindings for RTags conflicts with GTags
     -TODO: Not working with the build system at work.
     -TODO: Flycheck is lagging behind when using rtags.
     #+BEGIN_SRC emacs-lisp
       (use-package rtags
         :disabled t
         :init
         (use-package flycheck-rtags
           :config
           (defun my-flycheck-rtags-setup ()
             (flycheck-select-checker 'rtags)
             (setq-local flycheck-highlighting-mode nil) ;; RTags creates more accurate overlays.
             (setq-local flycheck-check-syntax-automatically nil))
           (add-hook 'c-mode-hook #'my-flycheck-rtags-setup)
           (add-hook 'c++-mode-hook #'my-flycheck-rtags-setup)
           (add-hook 'objc-mode-hook #'my-flycheck-rtags-setup)
           :pin melpa-stable)
         :bind (("M-." . rtags-find-symbol-at-point)
                ("M-," . rtags-find-references-at-point)
                ("M-[" . rtags-location-stack-back)
                ("M-]" . rtags-location-stack-forward))
         :config
         (setq rtags-autostart-diagnostics t)
         (rtags-diagnostics)
         (setq rtags-completions-enabled t)
         ;; (push `company-rtags company-backends)
         :pin melpa-stable)
     #+END_SRC
*** Format
    #+BEGIN_SRC emacs-lisp
      (use-package clang-format
        :bind ("C-<tab>" . clang-format-region)
        :pin melpa)
    #+END_SRC
** Languages
  Modes for highlighting different programing languages.
*** Functional
**** Haskell
     Settings for programming haskell in emacs
     #+BEGIN_SRC emacs-lisp
       (use-package haskell-mode
       	 :config
       	 (add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)
       	 (add-hook 'haskell-mode-hook 'turn-on-haskell-indent)
       	 (autoload 'ghc-init "ghc" nil t)
       	 :pin melpa-stable)
     #+END_SRC
**** Lisp
     Color haxvalues with their respective color.
     #+BEGIN_SRC emacs-lisp
       (use-package lisp-mode
	 :ensure nil ; Built in
	 :config
	 (defvar hexcolour-keywords
	   '(("#[[:xdigit:]]\\{6\\}"
	      (0 (put-text-property (match-beginning 0)
				    (match-end 0)
				    'face (list :background 
					       	(match-string-no-properties 0)))))))
	 (defun hexcolour-add-to-font-lock ()
	   (font-lock-add-keywords nil hexcolour-keywords))
	 (add-hook 'lisp-mode-hook 'hexcolour-add-to-font-lock))
     #+END_SRC
*** C family
    Specific for C, C++ and other in the c family
    - Set indentation to be two spaces.
    - Set the default mode for .h files to be c++-mode
    - Make it easier to work with camelCase words by enabling subword-mode.
    - Add that it will also search src and include directories when
      switching between header and source files.

    Custom style based on gnu for work. See [[https://www.gnu.org/software/emacs/manual/html_node/ccmode/Adding-Styles.html#Adding-Styles][adding-styles]] for more
    info how this work. [[https://www.gnu.org/software/emacs/manual/html_node/ccmode/Guessing-the-Style.html][Guessing]] the style also work, but it was
    easier for me to just place the pointer at a location and press
    C-c C-o (c-set-offset) and add that to the c-offsets-alist.
    #+BEGIN_SRC emacs-lisp
      (c-add-style "dd"
                   '("gnu"
                     (c-basic-offset . 2)
                     (c-offsets-alist
                      (substatement-open . 0)
                      (arglist-close . 0)
                      (statement-case-open . 0))))
    #+END_SRC
    #+BEGIN_SRC emacs-lisp
      (use-package cc-mode
        :mode ("\\.h\\'" . c++-mode)
        :config
        (add-hook 'c-mode-common-hook
                  (lambda ()
                    (setq indent-tabs-mode nil)
                    (when dotemacs-is-work (c-set-style "dd"))
                    (subword-mode 1))) ;; enable camelCase
        (setq ff-search-directories '("." "../src" "../include"))
        :pin melpa-stable)

    #+END_SRC
*** Python
    Package name is python but the mode is python-mode
    Set indentation to 2 white spaces.

    Set the default for pb2 files (=PROJECT=) to use python.
    #+BEGIN_SRC emacs-lisp
      (use-package python
       	:mode (("\\.py\\'" . python-mode) 
               ("PROJECT$" . python-mode))
       	:interpreter ("python" . python-mode)
       	:config

       	(setq python-mode-hook
              (function (lambda ()
                          (setq indent-tabs-mode nil)
                          (setq python-indent-offset 
                               	(if dotemacs-is-work 4 2)))))
       	:pin melpa-stable)
    #+END_SRC
*** Rust
    
    Packages for setting up a rust environment
    #+BEGIN_SRC emacs-lisp
      (use-package rust-mode
        :pin melpa-stable)
    #+END_SRC
    
    Mode for editing Cargo files.
    #+BEGIN_SRC emacs-lisp
      (use-package toml-mode
        :pin melpa)
    #+END_SRC
    
    Add key combinations to perform cargo tasks within a Rust project.
    #+BEGIN_SRC emacs-lisp
      (use-package cargo
        :init
        (add-hook 'rust-mode-hook 'cargo-minor-mode)
        :pin melpa-stable)
    #+END_SRC

    Lint rust code with flycheck
    #+BEGIN_SRC emacs-lisp
      (use-package flycheck-rust
        :pin melpa)
    #+END_SRC

*** Golang
    Setting up go to use 2 spaces as indentation and enable
    autocomplete for go.
    #+BEGIN_SRC emacs-lisp
      (use-package go-mode
       	:config
       	(add-hook 'go-mode-hook 
                  (lambda ()
                    (setq-default) 
                    (setq tab-width 2) 
                    (setq standard-indent 2) 
                    (setq indent-tabs-mode nil)))
       	(use-package go-autocomplete
          :pin melpa-stable)
       	:pin melpa-stable)
    #+END_SRC
*** Shaders
**** GLSL
     Set files associated with glsl to use glsl mode
     #+BEGIN_SRC emacs-lisp
       (use-package glsl-mode
         :mode (("\\.vert\\'" . glsl-mode)
               	("\\.frag\\'" . glsl-mode)
               	("\\.geom\\'" . glsl-mode)
               	("\\.prog\\'" . glsl-mode)
               	("\\.glsl\\'" . glsl-mode))
         :pin melpa)
     #+END_SRC

*** Build
**** Makefile
     Set following files to use makefile-gmake-mode as the default.
     - Files that starts with =Makefile=.
     - Has extension =.mk=.
     - Files that are located in a directory called Make and ends with
       =Rules=.
     - Files that are located in a directory called =modules=.
     - Files called =BUILD.conf= (pb2 file).
     - Files called =Project= that are located in a directory called Make.
     - Has extension =.tdpackage=.
     #+BEGIN_SRC emacs-lisp
       (use-package make-mode
       	 :mode (("Makefile.*" . makefile-gmake-mode)
               	("\\.mk$" . makefile-gmake-mode)
               	("Make/.*Rules$" . makefile-gmake-mode)
               	("modules/.*" . makefile-gmake-mode)
               	("BUILD\\.conf$" . makefile-gmake-mode)
               	("Make/Project$" . makefile-gmake-mode)
               	("\\.tdpackage$" . makefile-gmake-mode)
               	))
     #+END_SRC
**** CMake
     #+BEGIN_SRC emacs-lisp
       (use-package cmake-mode
       	 :pin melpa-stable)
     #+END_SRC
*** REPL
**** Geiser
     
     - *TODO:* Update to :hook when that comes available.

     #+BEGIN_SRC emacs-lisp
       (use-package geiser
         :init
         (add-hook 'scheme-mode-hook 'geiser-mode)
         :config
         (setq geiser-default-implementation 'guile)
         :pin melpa-stable)
     #+END_SRC
     Auto complete backend for geiser
     #+BEGIN_SRC emacs-lips
	 (use-package ac-geiser
	   :pin melpa-stable)
     #+END_SRC
**** Sh
     Indent using 2 spaces for shell scripts.
     #+BEGIN_SRC emacs-lisp
       (use-package sh-script
       	 :config
       	 (add-hook 'sh-mode-hook
               (lambda ()
               	 (setq indent-tabs-mode nil)
               	 (setq c-basic-offset 2))))
     #+END_SRC
*** Yaml
    #+BEGIN_SRC emacs-lisp
      (use-package yaml-mode
       	:pin melpa-stable)
    #+END_SRC
*** Sphinx (disabled)

    - *FIXME: * Getting failed to open file f
    #+BEGIN_SRC emacs-lisp
      (use-package sphinx-mode
       	:disabled t
       	:pin melpa-stable)
    #+END_SRC
*** Markdown
    #+BEGIN_SRC emacs-lisp
      (use-package markdown-mode
       	:pin melpa-stable)   
    #+END_SRC
*** Meson
   #+BEGIN_SRC emacs-lisp
     (use-package meson-mode
       :pin melpa-stable)
   #+END_SRC
*** Julia
    #+BEGIN_SRC emacs-lisp
      (use-package julia-mode
        :init
        :pin melpa-stable)
    #+END_SRC
*** Systemd
    #+BEGIN_SRC emacs-lisp
      (use-package systemd
        :init
        :pin melpa-stable)
    #+END_SRC
** Programs
  Packages that communicates with external processes.
*** Ledger
   Settings for ledger.
   Set the default mode for .dat files to ledger.

   Clean the buffer with C-c c.
   #+BEGIN_SRC emacs-lisp
     (use-package ledger-mode
       :bind (:map ledger-mode-map ("C-c c" . ledger-mode-clean-buffer))
       :mode "\\.dat\\'"
       :config
       (setq ledger-clear-whole-transactions 1)
       (add-hook 'ledger-mode-hook 
                 (lambda ()
                   (company-mode -1)))
:pin melpa-stable)
   #+END_SRC   
*** Arduino
    Function for setting up a arduino template sketch
    #+BEGIN_SRC emacs-lisp
      (defun init-arduino ()
      "Template arduino sketch"
      (interactive)
      (insert "void setup() {
       	// put your setup code here, to run once:

      }

      void loop() {
       	// put your main code here, to run repeatedly:

      }")
      )   
    #+END_SRC
*** Multi term
    #+BEGIN_SRC emacs-lisp
      (use-package multi-term
       	:pin melpa)
    #+END_SRC
*** Gnuplot
    Enable gnuplot to be able to plot tables in org mode.

    Bind the F9 key to open a buffer into gnuplot mode

    Set that all files ending in .gp will use the gnuplot-mode
    #+BEGIN_SRC emacs-lisp
      (use-package gnuplot
       	:bind ([(f9)] . gnuplot-make-buffer)
       	:config
       	(autoload 'gnuplot-mode "gnuplot" "gnuplot major mode" t)
       	(autoload 'gnuplot-make-buffer "gnuplot" "open a buffer in gnuplot mode" t)
       	;; Set files with ext .gp to use gnuplot
       	(setq auto-mode-alist (append '(("\\.gp$" . gnuplot-mode)) auto-mode-alist))
       	:pin melpa-stable)
    #+END_SRC
*** Magit
    A Git porcelain inside Emacs
    Key =C-x g= to run magit on current buffer.

    #+BEGIN_SRC emacs-lisp
      (use-package magit
       	:bind ( "C-x g" . magit-status)
       	:pin melpa-stable)
    #+END_SRC
*** The Silver Searcher
    #+BEGIN_SRC emacs-lisp
      (use-package ag
	:pin melpa-stable)
    #+END_SRC

** Web
  Packages for webbased content.
*** nginx
    Major mode for editing nginx.
    #+BEGIN_SRC emacs-lisp
      (use-package nginx-mode
       	:pin melpa-stable)
    #+END_SRC
** Emacs
  Packages that augments emacs.
*** Org

    Mostly from [[https://github.com/hrs/dotfiles/tree/master/emacs.d][hrs]] config file but converted to use-package.

    Use a little downward-pointing arrow instead of the usual ellipsis
    (=...=) when folded.

    Use syntax highlighting in source blocks while editing
    'org-src-fontify-natively'.

    #+BEGIN_SRC emacs-lisp
      (use-package org
	:mode ("\\.org\\'" . org-mode)
	:bind (("C-c l" . org-store-link)
	       ("C-c a" . org-agenda)
	       ("C-c c" . org-capture)
	       ("C-c b" . org-iswitchb))
	:config
	(use-package org-bullets
	  :pin melpa-stable)
	;; Use pretty bullet points instead of asterix
	(add-hook 'org-mode-hook
		  (lambda ()
		    (org-bullets-mode t)))
	(setq org-ellipsis "⤵"
	      org-src-fontify-natively t
	      org-todo-keywords
	      '((sequence "TODO(t)" "WAIT(w@/!)" "|" "DONE(d!)" "CANCELLED(c@)")))
	(when (not dotemacs-is-work)
	  (add-to-list 'org-agenda-files "~/syncthing/Orgzly/"))

	;; Active Babel languages
	(org-babel-do-load-languages
	 'org-babel-load-languages
	 '((scheme . t)))
	;; (setq org-src-window-setup 'current-window)
	:pin org)
    #+END_SRC

    Doesn't work with yasnippet getting:
    yas--fallback: yasnippet fallback loop!
    This can happen when you bind ‘yas-expand’ outside of the ‘yas-minor-mode-map’.

    Make TAB act as if it were issued in a buffer of the language's major mode.
    =(setq org-src-tab-acts-natively t)=
*** Buffer move
    Move buffers around between windows
    #+BEGIN_SRC emacs-lisp
      (use-package buffer-move 
       	:bind ( ("<M-S-up>"    . buf-move-up)
               	("<M-S-down>"  . buf-move-down)
               	("<M-S-left>"  . buf-move-left)
               	("<M-S-right>" . buf-move-right))
       	:pin melpa-stable)
    #+END_SRC
*** Dired
    Settings for dired.
    Source for the afs-dired-find-file function: [[https://stackoverflow.com/questions/1110118/in-emacs-dired-how-to-find-visit-multiple-files][Source]]
    #+BEGIN_SRC emacs-lisp
      (use-package dired
       	:ensure nil
       	;; Map afs-dired-find-file to F
       	:bind (:map dired-mode-map 
               ("F" . afs-dired-find-file))
       	:config
       	(defun afs-dired-find-file (&optional arg)
             "Open each of the marked files, or the file under the
           point, or when prefix arg, the next N files "
             (interactive "P")
             (let ((fn-list (dired-get-marked-files nil arg)))
               (mapc 'find-file fn-list))))
    #+END_SRC
*** ibuffer
     Use ibuffer instead of list-buffers, has some neat features.

     Sort buffers by placing them in different groups
     #+BEGIN_SRC emacs-lisp
       (use-package ibuffer
         :config 
         (defalias 'list-buffers 'ibuffer)
         (setq ibuffer-saved-filter-groups
             (quote (("default"
                      ("c++" (mode . c++-mode))
                      ("make"  (or (mode . makefile-gmake-mode)
                                   (mode . makefile-mode)))
                      ("cmake" (mode . cmake-mode ))
                      ("ag" (mode . ag-mode ))
                      ("docs" (mode . rst-mode))
                      ("org" (mode . org-mode))
                      ("dired" (mode . dired-mode))
                      ("python" (mode . python-mode))
                      ("vc" (mode . vc-dir-mode))
                      ("magit" (name . "^\\*magit"))
                      ("shell" (mode . shell-mode))
                      ("emacs" (name . "^\\*[[:alnum:]]+\\*$"))
                      ))))
       (add-hook 'ibuffer-mode-hook
                 (lambda ()
                   (ibuffer-switch-to-saved-filter-groups "default"))))
     #+END_SRC
*** Helm (Disabled)
    Disabled because it did horrible with tramp
    Settings for helm

    #+BEGIN_SRC emacs-lisp
      (use-package helm
        :disabled t
        :init
        ;; List git and svn projects with helm-browse-project
        (use-package helm-ls-git
          :pin melpa-stable)
        :bind (("M-x" . helm-M-x)
               ("M-y" . helm-show-kill-ring)
               ("C-x C-f" . helm-find-files)
               ("<tab>" . helm-execute-persistent-action)
               ("C-i" . helm-execute-persistent-action) ;; make TAB work in terminal
               ("C-z" . helm-select-action))
        :config
        (helm-autoresize-mode t)
        (helm-mode 1)
        :pin melpa-stable)
         
    #+END_SRC
*** Tramp
    Set the ssh to be the default method for tramp.
    If tramp hangs and you are using zsh see [[#tramp-hang-workaround][here]].
    #+BEGIN_SRC emacs-lisp
      (use-package tramp
        :config
        (setq tramp-default-method "ssh")
        (add-to-list 'tramp-remote-path "~/bin")
        (add-to-list 'tramp-remote-path "/tools/bin")
        (add-to-list 'tramp-remote-path "~/.guix-profile/bin")
        (add-to-list 'tramp-remote-path "~/.guix-profile/sbin")
        (add-to-list 'tramp-remote-path "/run/current-system/profile/bin")
        (add-to-list 'tramp-remote-path "/run/current-system/profile/sbin"))
    #+END_SRC
*** Sudo edit
    Sudo edit the current file
    #+BEGIN_SRC emacs-lisp
      (use-package sudo-edit
       	:bind ("C-c C-r" . sudo-edit)
       	:pin melpa)
    #+END_SRC
*** Powerline (Disabled)
    #+BEGIN_SRC emacs-lisp
      (use-package powerline
       	:disabled
       	:config
       	(powerline-vim-theme)
       	:pin melpa-stable)
    #+END_SRC
*** Windmove
    Jump between windows using the arrow keys instead of cycling with
    "C-x o". Note that this Doesn't work in org mode.
    #+BEGIN_SRC emacs-lisp
      (use-package windmove 
       	:bind (([M-left]  . windmove-left)  ; move to left window
               ([M-right] . windmove-right) ; move to right window
               ([M-up]    . windmove-up)    ; move to upper window
               ([M-down]  . windmove-down)) ; move to downer window
       	:pin melpa-stable)
    #+END_SRC
*** avy
    #+BEGIN_SRC emacs-lisp
      (use-package avy
        :config
        (setq avy-all-windows nil)
        (setq avy-background t)
        :bind (("M-s" . avy-goto-char))
        :pin melpa-stable)
    #+END_SRC
*** Compilation

    Ansi colors in compilation window see [[https://stackoverflow.com/questions/13397737/ansi-coloring-in-compilation-mode][link]]
    For closing compilation window when it's done see [[https://www.emacswiki.org/emacs/ModeCompile#toc2][link]]

    TODO: Fix that when closing the *compilation* buffer that it picks
    a buffer that's not already active. Which it does right now and is
    quite annoying. Have disabled it because of that.
    #+BEGIN_SRC emacs-lisp
      (use-package compile 
        :init
        ;; Reuse the *compilaiton* window if open if not pick another window
        ;; in another frame.
        (add-to-list 'display-buffer-alist
                     '("^\\*compilation\\*$"
                       (display-buffer-reuse-window display-buffer-use-some-frame)
                       (reusable-frames      . visible)
                       (inhibit-switch-frame . t)
                       (inhibit-same-window  . t)
                       ))
        :config
        (use-package ansi-color)
        (add-hook 'compilation-filter-hook 
                  (lambda ()
                    (toggle-read-only)
                    (ansi-color-apply-on-region compilation-filter-start (point))
                    (toggle-read-only)))
        ;; ;; Close the compilation window if there was no error at all.
        ;; (setq compilation-exit-message-function
        ;;       (lambda (status code msg)
        ;;         ;; If M-x compile exists with a 0
        ;;         (when (and (eq status 'exit) (zerop code))
        ;;           ;; then bury the *compilation* buffer, so that C-x b doesn't go there
        ;;           (bury-buffer "*compilation*")
        ;;           ;; and return to whatever were looking at before
        ;;           (replace-buffer-in-windows "*compilation*"))
        ;;         ;; Always return the anticipated result of compilation-exit-message-function
        ;;         (cons msg code)

      )
    #+END_SRC
*** Version Control
    Don't ask when following a symlink to a vc directory.
    #+BEGIN_SRC emacs-lisp
      (setq vc-follow-symlinks t)
    #+END_SRC
** Text
  Packages for editing text.
*** Rainbow (Disabled)
    #+BEGIN_SRC emacs-lisp
      (use-package rainbow-mode
       	:disabled t
       	:pin melpa-stable)
    #+END_SRC
*** Smartparens (Disabled)
    Having issues with turning of auto balancing, i.e
    (|) - insert () -> (()|
    #+BEGIN_SRC emacs-lisp
      (use-package smartparens
       	:disabled t
       	:init
       	(add-hook 'c-mode-hook 'turn-on-smartparens-mode)
       	(add-hook 'c++-mode-hook 'turn-on-smartparens-mode)
       	(add-hook 'lisp-mode-hook 'turn-on-smartparens-mode)
       	(add-hook 'scheme-mode-hook 'turn-on-smartparens-mode)
       	(add-hook 'guile-mode-hook 'turn-on-smartparens-mode)
       	(add-hook 'python-mode 'turn-on-smartparens-mode)
       	(add-hook 'lisp-interaction-mode-hook 'turn-on-smartparens-mode)
       	:bind (("M-k" . sp-kill-hybrid-sexp)
	       ("C-M-k" . sp-backward-kill-sexp)
	       ("C-)" . sp-forward-slurp-sexp)
	       ("C-(" . sp-backward-slurp-sexp)
	       ("C-}" . sp-forward-barf-sexp)
	       ("C-{" . sp-backward-barf-sexp)
	       ("C-M-a" . sp-beginning-of-sexp)
	       ("C-M-e" . sp-end-of-sexp)
	       ("C-M-t" . sp-transpose-hybrid-sexp)
	       ("C-M-s" . sp-splice-sexp)
	       ("M-s" . sp-split-sexp)
	       ("M-[" . sp-backward-unwrap-sexp)
	       ("M-]" . sp-unwrap-sexp)
	       ("M-}" . sp-splice-sexp-killing-backward)
	       ("M-{" . sp-splice-sexp-killing-forward))
       	:config
       	(setq sp-autoinsert-pair nil)
       	(setq sp-autoskip-closing-pair nil)
       	:pin melpa-stable)
    #+END_SRC
*** Paredit (Disabled)
    Cannot set custom keybindings, conflicts with my movement keys.

    ParEdit is a minor mode for performing structured editing of
    S-expression data.
    #+BEGIN_SRC emacs-lisp
      (use-package paredit
       	:disabled t
       	:bind (("C-)" . paredit-forward-slurp-sexp)
	       ("C-(" . paredit-backward-slurp-sexp)
	       ("C-}" . paredit-forward-barf-sexp)
	       ("C-{" . paredit-backward-barf-sexp)
	       ("M-{" . paredit-splice-sexp-killing-backward)
	       ("M-}" . paredit-splice-sexp-killing-forward))
       	:init
       	(autoload 'enable-paredit-mode "paredit" "Turn on pseudo-structural editing of Lisp code." t)
       	(add-hook 'emacs-lisp-mode-hook       #'enable-paredit-mode)
       	(add-hook 'eval-expression-minibuffer-setup-hook #'enable-paredit-mode)
       	(add-hook 'ielm-mode-hook             #'enable-paredit-mode)
       	(add-hook 'lisp-mode-hook             #'enable-paredit-mode)
       	(add-hook 'lisp-interaction-mode-hook #'enable-paredit-mode)
       	(add-hook 'scheme-mode-hook           #'enable-paredit-mode)
       	:pin melpa-stable)
    #+END_SRC

*** Evil numbers
    Incrementing/decrementing numbers.
    #+BEGIN_SRC emacs-lisp
      (use-package evil-numbers
       	:bind (("C-c +" . evil-numbers/inc-at-pt)
	       ("C-c -" . evil-numbers/dec-at-pt))
       	:pin melpa-stable)
    #+END_SRC
*** Move text
    Move line up and down using arrow keys.
    #+BEGIN_SRC emacs-lisp
      (use-package move-text
       	:bind (([C-S-up] . move-text-up)
               ([C-S-down] . move-text-down))
       	:pin melpa-stable)
    #+END_SRC

*** Expand region
    #+BEGIN_SRC emacs-lisp
      (use-package expand-region
       	:bind ("C-=" . er/expand-region)
       	:pin melpa-stable)
    #+END_SRC
*** Multiple cursors
    Keybindings for the mc package
    #+BEGIN_SRC emacs-lisp
      (use-package multiple-cursors 
        :bind (("C-S-c C-S-c" . mc/edit-lines)
               ("C->"         . mc/mark-next-like-this)
               ("C-<"         . mc/mark-previous-like-this)
               ("C-c C-<"     . mc/mark-all-like-this)
               ("C-+"         . mc/mark-next-like-this)
               ("C-c m n"     . mc/insert-numbers)
               ("C-c m c"     . mc/insert-characters)
               ("C-c m s n"   . mc/insert-same-numbers-per-line)
               ("C-c m s c"   . mc/insert-same-chars-per-line))
        :config
        (use-package mc-extras
          :pin melpa-stable)
        :pin melpa-stable)
    #+END_SRC
*** String inflections
    Keybinding for cycle between snake case, camel case etc
    #+BEGIN_SRC emacs-lisp
      (use-package string-inflection 
       	:bind ("C-;" . string-inflection-cycle )
       	:pin melpa-stable)
    #+END_SRC
*** fancy-narrow
    Highlight section of code, run 'fancy-narrow-to-region' to narrow
    down on selection.  'fancy-widen' to go back to
    normal. 'fancy-narrow-to-defun' to narrow down on function.
    #+BEGIN_SRC emacs-lisp
      (use-package fancy-narrow
        :pin melpa-stable)
    #+END_SRC
** Nov
   Epub reader mode.
   #+BEGIN_SRC emacs-lisp
     (use-package nov
       :mode (("\\.epub\\'" . nov-mode))
       :pin melpa-stable)
   #+END_SRC
** Shell
   Enable color in shell and define the color theme. Also disable
   yasnippet in shell mode since that's messing with the shell.
   
   Disabled the comint-highlight-prompt to use the colors from the
   shells prompt. Source: [[https://stackoverflow.com/questions/25819034/colors-in-emacs-shell-prompt][link]].

   Custom function to clear the shell in emacs. Bound to f8
   #+BEGIN_SRC emacs-lisp
     (use-package shell
       :bind ("<f8>" . clear-shell)
       :init
       :config
       ;; Use the prompts colours instead of ansi-color
       (set-face-attribute 'comint-highlight-prompt nil
                           :inherit nil)

       (add-hook 'shell-mode-hook 
                 (lambda ()
                   ;; Enable color in shell
                   (ansi-color-for-comint-mode-on)
                   ;; Change Color theme in shell
                   (setq ansi-color-names-vector
                         ["#4d4d4d"
                          "#D81860"
                          "#60FF60"
                          "#f9fd75"
                          "#4695c8"
                          "#a78edb"
                          "#43afce"
                          "#f3ebe2"])
                   (setq ansi-color-map (ansi-color-make-color-map))
                   ;; Disable yas minor mode
                   (yas-minor-mode -1)
                   ;; Disable company mode
                   ;; Breaks find-*dired functions
                   ;;(when (not dotemacs-is-work) (company-mode -1))
                   ;; Add go and goc to the dirtrack, Need tweak the regexp 
                   ;; (setq shell-cd-regexp "\\(cd\\|goc\\|go\\)")
                   ))
       (defun clear-shell ()
         "Clear the shell buffer"
         (interactive)
         (let ((comint-buffer-maximum-size 0))
           (comint-truncate-buffer))))
   #+END_SRC
* Work
** Behaviour
   #+BEGIN_SRC emacs-lisp
     (when dotemacs-is-work (setq explicit-shell-file-name "/bin/bash"))
   #+END_SRC

   Store work related settings.
   #+BEGIN_SRC emacs-lisp
     (when dotemacs-is-work 
       (when (file-exists-p "~/.emacs.d/.work.el") 
         (load "~/.emacs.d/.work.el")))
   #+END_SRC
** Custom packages
*** dd-newfile
    Function that inserts the DD template for a new file
    #+BEGIN_SRC emacs-lisp
      (use-package dd-newfile
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
*** dd-log-parser
    Functions for parsing the =DD::Logger=
    #+BEGIN_SRC emacs-lisp
      (use-package dd-log-parser
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
*** dd-pybuild2
    #+BEGIN_SRC emacs-lisp
      (use-package dd-pybuild2
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
*** houdini
    Houdini related functions, mostly handle houdini versions.
    #+BEGIN_SRC emacs-lisp
      (use-package houdini
        :bind ("C-x j" . hou-insert-version)
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
*** highlight-extra
    Functions for highlighting my shells when building etc
    #+BEGIN_SRC emacs-lisp
      (use-package highlight-extra
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
*** work
    Bunch of functions to setup my work area when at work 
    #+BEGIN_SRC emacs-lisp
      (use-package work
        :if dotemacs-is-work
        :ensure nil
        :load-path "~/.emacs.d/plugins")
    #+END_SRC
** Custom functions
*** PID    
   Get the pid of a proc
   #+BEGIN_SRC emacs-lisp
     (defun pid (regex &optional index)
       "Get the pid of REGEX, if more than one is running it returns one
     at INDEX. Where INDEX starts from 0 and up"
       (interactive)
       (when (not index) (setq index 0))
       (nth index 
	    (split-string 
	     (shell-command-to-string
	      (concat "ps aux | " ;; wrap first character in [ ] to not match itself
		      "sed -nE \"s/$USER\\s+([0-9]+).*?"
		      (concat "[" (substring regex 0 1) "]" (substring regex 1))"/\\1/p\"")
	      ))))
   #+END_SRC
*** PID Houdini
    Get the PID for houdini
    #+BEGIN_SRC emacs-lisp
      (defun pid-houdini (&optional index )
	"Get the pid for houdini.
      If more than one is running it returns the one at INDEX.  Where
      INDEX starts from 0 and up"

	(interactive)
	(when (not index) (setq index 0)) (pid "houdini-bin" index))
    #+END_SRC
*** PID Maya
    #+BEGIN_SRC emacs-lisp
      (defun pid-maya (&optional index)
	"Get the pid for maya.
      If more than one is running it returns the one at INDEX.  Where
      INDEX starts from 0 and up"
	(interactive)
	(when (not index) (setq index 0))
	(pid "maya\\.bin" index))
    #+END_SRC
*** PID smeat
    #+BEGIN_SRC emacs-lisp
      (defun pid-smeat (&optional index)
	"Get the pid for smeat.
      If more than one is running it returns the one at INDEX.  Where
      INDEX starts from 0 and up"
	(interactive)
	(when (not index) (setq index 0))
	;; the ^= is to ignore houdini/python commands e.g houdini --with smeat=...
	(pid "smeat(:?[^=]+|$$)" index))
    #+END_SRC
*** Attach Houdini
    Used with gdb, prints attach <pid of houdini> in the prompt.
    #+BEGIN_SRC emacs-lisp
      (defun attach-houdini (&optional index)
	"Prints attach <pid> into the buffer. 
      INDEX is use to select which one if there are multiple instances
      running, INDEX counts from 1."
	(interactive"p")

	;; The default for index is one.
	(when (< index 1) (setq index 1))
	(insert (concat "attach " (pid-houdini (- index 1)) )))
    #+END_SRC
*** Attach Maya
    #+BEGIN_SRC emacs-lisp
      (defun attach-maya (&optional index) 
        "Prints attach <pid> into the buffer. 
      INDEX is use to select which one if there are multiple instances
      running, INDEX counts from 1."
        (interactive"p")
        ;; The default for index is one.
        (when (< index 1) (setq index 1))
        (insert (concat "attach " (pid-maya index) )))
    #+END_SRC
*** Attach smeat
    #+BEGIN_SRC emacs-lisp
      (defun attach-smeat (&optional index)
	"Prints attach <pid> into the buffer.
      INDEX is use to select which one if there are multiple instances
      running, INDEX counts from 1."
	(interactive"p")

	;; The default for index is one.
	(when (< index 1) (setq index 1))
	(insert (concat "attach " (pid-smeat (- index 1)) )))
    #+END_SRC
*** Kill Houdini
    #+BEGIN_SRC emacs-lisp
      (defun kill-houdini ()
        "Kill houdini.
      If more than one houdini are running it will kill the
      first one in the ps list."
        (interactive)
        (shell-command (concat "kill -9 " (pid-houdini))))
    #+END_SRC
*** Kill Maya 
    #+BEGIN_SRC emacs-lisp
      (defun kill-maya ()
        "Kill maya.
      If more than one Maya process are running it will kill the
      first one in the ps list."
        (interactive)
        (shell-command (concat "kill -9 " (pid-maya))))
    #+END_SRC
*** Smeat abort
    Not quite working. But sends a signal to the smeat process to abort the sim.
    #+BEGIN_SRC emacs-lisp
      (defun smeat-abort (&optional index )
        "Sends USR1 signal to houdini which aborts the smeat client.
      INDEX is used to select which houdini instance to send to if
      multiple instances exist."
        (interactive"p")
        (when (< index 1) (setq index 1))
        (let ((hou-pid (pid-houdini index)))
          (shell-command (concat "kill -s USR1 " hou-pid))))
    #+END_SRC
*** Preproccess
    #+BEGIN_SRC emacs-lisp
      (defun preprocess-fix-macros ()
        "Fix expanded macros when running only the preprocess on a file.
      For example: g++ <flags> -E <file>.  Since they are expanded into
      a single line which makes them hard to debug."
        (interactive)
        (let* ((start (if (use-region-p) (region-beginning) (point)))
               (end (if (use-region-p) (region-end) (point-max)))
               (regex-map '(":[ ]" ";" "{" "}[ ]"))
               (regex (mapconcat (lambda (x) (format "\\(%s\\)" x)) regex-map "\\|")))
          (goto-char start)
          (while (search-forward-regexp regex end t)
            (newline)
            (setq end (1+ end)))
          (indent-region start (point))
          (goto-char start)))
    #+END_SRC
*** Make
    Functions to speed up the port of old style Makefiles to using modules.
    #+BEGIN_SRC emacs-lisp
      (defun make-boost-components ()
        "Convert old style boost libs to module style"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          (while (re-search-forward
                  (concat "\\$(\\(?:EXECS\\|LIBS\\))_LIBS \\+= "
                          "\\$(BOOST_LIB_DIR)/libboost_\\(.*?\\)\\.a") end t)
            (replace-match "BOOST_COMPONENTS += \\1"))))

      (defun make-include-to-modules ()
        "Convert old Makefile's INCLUDE to using modules"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          (while (re-search-forward
                  "INCLUDES \\+= \\$(\\(.*\\)_INC_DIR)" end t)
            (replace-match 
             (concat "MODULES += " (downcase (match-string-no-properties 1))) t ))))

      (defun make-mkl-module ()
        "Convert old mkl static libs to using the mkl module's flags"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          (when (re-search-forward 
                 (concat "\\$(\\(?:EXECS\\|LIBS\\))_LIBS \\+= " 
                         "\\$(MKL_STATIC_LAYERED_LIBS)") end t)
            (replace-match "MKL_USE_STATIC_LIBS = YES"))))

      (defun make-eigen-module ()
        "Convert eigen cxxflag to using the eigen module's flags"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          (when (re-search-forward 
                 "X?CXXFLAGS \\+= -DEIGEN_USE_MKL_ALL" end t)
            (replace-match "EIGEN_USE_MKL = YES"))))

      (defun make-openvdb-module ()
        "Convert openvdb cxxflag to using the openvdb module's flags"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          (when (re-search-forward 
                 "X?CXXFLAGS \\+= -DOPENVDB_3_ABI_COMPATIBLE" end t)
            (replace-match "OPENVDB_USE_ABI_3 = YES"))))

      (defun make-insert-toolchain (&optional toolchain)
        "Insert TOOLCHAIN = TOOLCHAIN, where the last is the variable TOOLCHAIN."
        (interactive "sName of toolchain to use: ")
        
        (when (not toolchain) (setq toolchain "gcc") )
        
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end nil)))
          (goto-char begin)
          ;; Move to the end of the _SRCS
          (while (re-search-forward "\\$(\\(?:EXECS\\|LIBS\\))_SRCS \\+= .*" end t))
          
          (insert (concat "\n\nTOOLCHAIN = " toolchain))))

      (defun make-delete-libpaths-and-rpath ()
        "Delete LIBPATHS += and RPATH_LIBSPATHS from the makefile"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end (point-max))))
          (delete-matching-lines "\\(?:RPATH_\\)?LIBPATHS \\+= .*" begin end )))

      (defun make-delete-libs ()
        "Delete $(EXECS/LIBS)_LIBS += lines from the makefile"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point-min) end (point-max))))
          (delete-matching-lines "\\$(\\(?:EXECS\\|LIBS\\))_LIBS \\+= .*" begin end )))

      (defun convert-make-to-modules ()
        "Convert old makefile to using modules"
        (interactive)
        (make-insert-toolchain)
        (make-include-to-modules)
        (make-mkl-module)
        (make-eigen-module)
        (make-openvdb-module)
        (make-boost-components)
        (make-delete-libpaths-and-rpath)
        (make-delete-libs))
    #+END_SRC
* Custom functions
** Buffer
   Function for renaming buffer and file. [[http://www.stringify.com/2006/apr/24/rename/][Source]]
   #+BEGIN_SRC emacs-lisp
     (defun rename-current-file-or-buffer ()
       "Rename current file and buffer, similar to save-as but removes
     the old file"
       (interactive)
       (if (not (buffer-file-name))
           (call-interactively 'rename-buffer)
         (let ((file (buffer-file-name)))
           (with-temp-buffer
             (set-buffer (dired-noselect file))
             (dired-do-rename)
             (kill-buffer nil))))
       nil)
   #+END_SRC
   To sync all open buffers with their respective files on disk. [[https://www.emacswiki.org/emacs/RevertBuffer][Source]]
   #+BEGIN_SRC emacs-lisp
     (defun revert-all-buffers ()
         "Refreshes all open buffers from their respective files."
         (interactive)
         (dolist (buf (buffer-list))
           (with-current-buffer buf
             (when (and (buffer-file-name) (not (buffer-modified-p)))
               (revert-buffer t t t) )))
         (message "Refreshed open files.") )
   #+END_SRC
** Text
   Taken from [[http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs][here]], author mk-fg.
   #+BEGIN_SRC emacs-lisp
     (defun duplicate-line ()
       "Clone line at cursor, leaving the latter intact."
       (interactive)
       (save-excursion
         (let ((kill-read-only-ok t) deactivate-mark)
           (read-only-mode 1)
           (kill-whole-line)
           (read-only-mode 0)
           (yank))))
   #+END_SRC
** Subversion

   #+BEGIN_SRC emacs-lisp
     (defun svn-fetch-info (item)
       "Get the info ITEM from the current svn repo as a string,
     can be for example url or revision, see svn info --help for the
     exhaustive list."
       (shell-command-to-string
        (concat "env PATH=" (getenv "PATH") " "
                "svn info --show-item=" item " --no-newline")))
   #+END_SRC

   #+BEGIN_SRC emacs-lisp
     (defun svn-fetch-repo-url ()
       "Return a string of the repo url in the current svn repo.
          I.e the root url plus the name of the repo on the
          server. Prefixed will return the full url otherwise it will
          just return the relative."
       (let ((relurl (svn-fetch-info 
                      (if current-prefix-arg "url" "relative-url"))))
         (replace-regexp-in-string 
          "^\\(.*\\)/\\(trunk\\|tags.*\\|branches.*\\)"
          "\\1"
          relurl)))
   #+END_SRC
   
   
   Fetches the url of the repository. For example
   if we have the url
   http://svn.example.com/myrepo/branches/branch
   It will return the whole thing.
   
   #+BEGIN_SRC emacs-lisp
     (defun svn-url ()
       "Get the repo url in the current svn repo.
          I.e the root url plus the name of the repo on the server"
       (interactive)
       (insert (svn-fetch-info "url")))
   #+END_SRC

   Fetches the root url. For example if we have the url
   http://svn.example.com/myrepo/branches/branch
   ^^^^^^^^^^^^^^^^^^^^^^
   This is the root url.

   #+BEGIN_SRC emacs-lisp
     (defun svn-root-url ()
       "Get the repo's root url in the current svn repo."
       (interactive)
       (insert (svn-fetch-info "repos-root-url")))
   #+END_SRC

   Fetches the root url + the name of the repository. For example
   if we have the url
   http://svn.example.com/myrepo/branches/branch
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   This is the repo url.

   #+BEGIN_SRC emacs-lisp
     (defun svn-repo-url ()
       "Get the repo url in the current svn repo.
          I.e the root url plus the name of the repo on the
          server. Prefixed will return the full url otherwise it will
          just return the relative."
       (interactive)
       (insert (svn-fetch-repo-url)))
   #+END_SRC

   Get the trunk/branch/tag url for the current svn repo. For example
   if we have the url
   http://svn.example.com/myrepo/branches/branch

   It will return for svn-trunk-url
   http://svn.example.com/myrepo/trunk

   It will return for svn-branch-url
   http://svn.example.com/myrepo/branches

   It will return for svn-branch-url
   http://svn.example.com/myrepo/tags

   #+BEGIN_SRC emacs-lisp
     (defun svn-trunk-url ()
       "Get the url for the trunk in the current svn repo."
       (interactive)
       (insert 
        (concat (svn-fetch-repo-url) "/trunk")))
   #+END_SRC

   #+BEGIN_SRC emacs-lisp
     (defun svn-branch-url ()
       "Get the url for the branch root in the current svn repo."
       (interactive)
       (insert 
        (concat (svn-fetch-repo-url) "/branches")))
   #+END_SRC

   #+BEGIN_SRC emacs-lisp
     (defun svn-tag-url ()
       "Get the url for the branch root in the current svn repo."
       (interactive)
       (insert 
        (concat (svn-fetch-repo-url) "/tags")))
   #+END_SRC

** Programming
*** C++
**** Expands a define macro for all matches in current buffer.
     #+BEGIN_SRC emacs-lisp
       (defun replace-define()
         "Evaluating the define variable.
       Place cursor on a #define <var> <content> and execute this command and it will
       replace all <var> with <content> in the file."
         (interactive)
         (let ((line (split-string (thing-at-point 'line) )))
                (if (equal (car line) "#define")
                    (let ((curr-pos (point)) ;; save current position
                          (end (point-max)))
                 ;; Jump to the end of line
                 (end-of-line)
                 ;; Replace the first with the second.
                 (while (re-search-forward (concat "\\_<"(nth 1 line)"\\_>") end t )
                        (replace-match (nth 2 line)))
                 ;; return to the same position
                 (goto-char curr-pos)
                 ;; move to the end of the line to indicate that it's done.
                 (end-of-line))
                  (message "Not a #define directive!" ))))
     #+END_SRC
**** Undo replace-define.
      #+BEGIN_SRC emacs-lisp
        (defun replace-define-undo()
          "Undoing the expansion of the define variable.
        Place cursor on a #define <var> <content> and execute this
         command and it will replace all <content> with <var> in the
         file."

          (interactive)
          (let ((line (split-string (thing-at-point 'line) )))
            (if (equal (car line) "#define")
                (let ((curr-pos (point)) ;; save current position
                      (end (point-max)))
                  ;; Jump to the end of line
                  (end-of-line)

                  ;; Replace the second with the first
                  (while (re-search-forward (nth 2 line) end t ) (replace-match (nth 1 line)))

                  ;; return to the same position
                  (goto-char curr-pos)
                  ;; move to the end of the line to indicate that it's done.
                  (end-of-line))
              (message "Not a #define directive!" ))))

       	  #+END_SRC

**** Convert typedef to c++11's alias
      #+BEGIN_SRC emacs-lisp
        (defun convert-typedef-to-using ()
          "Converts typedef statements to using statements"
          (interactive)
          (let ((begin) (end))
             (if (use-region-p)
                (progn (setq begin (region-beginning) end (region-end)))
              (progn (setq begin (point) end nil)))
             (goto-char begin)
            (while (re-search-forward
                    (concat "typedef \\(\\(?:typename \\)*"
                            "[[:print:]]+?\\)[ \t]+\\([[:alnum:]_]+\\)[ ]*;" )
                    end t )
              (replace-match "using \\2 = \\1;"))))
      #+END_SRC
**** Convert LinSys to LinAlg
     #+BEGIN_SRC emacs-lisp
       (defun convert-LinSys-Solver ()
         "Converts Physics::Fluids::LinSys to Math::LinAlg::Solver"
         (interactive)
         (let ((begin) (end))
           (if (use-region-p)
               (progn (setq begin (region-beginning) end (region-end)))
             (progn (setq begin (point) end nil)))
           (goto-char begin)
           (while (re-search-forward "Physics\\([^/:.]\\)" end t ) (replace-match "Math\\1"))
           (goto-char begin)
           (while (re-search-forward "Fluids\\([^/:.]\\)" end t ) (replace-match "LinAlg\\1"))
           (goto-char begin)
           (while (re-search-forward "LinSys\\([^/:.]\\)" end t ) (replace-match "Solver\\1"))

           (goto-char begin)
           (while (re-search-forward "Physics::Fluids::LinSys" end t ) 
             (replace-match "Math::LinAlg::Solver"))
           
           (goto-char (point-min))
           (while (re-search-forward "PHYSICS_FLUIDS_LINSYS" end t ) 
             (replace-match "MATH_LINALG_SOLVER"))
           (goto-char begin)))
     #+END_SRC
**** Convert LinAlg to LinSys
     #+BEGIN_SRC emacs-lisp
       (defun convert-Solver-LinSys ()
         "Converts Math::LinAlg::Solver to Physics::Fluids::LinSys"
         (interactive)
         (let ((begin) (end))
           (if (use-region-p)
               (progn (setq begin (region-beginning) end (region-end)))
             (progn (setq begin (point) end nil)))
           (goto-char begin)
           (while (re-search-forward "Math\\([^/:.]\\)" end t ) (replace-match "Physics\\1"))
           (goto-char begin)
           (while (re-search-forward "LinAlg\\([^/:.]\\)" end t ) (replace-match "Fluids\\1"))
           (goto-char begin)
           (while (re-search-forward "Solver\\([^/:.]\\)" end t ) (replace-match "LinSys\\1"))

           (goto-char begin)
           (while (re-search-forward "Math::LinAlg::Solver" end t ) 
             (replace-match "Physics::Fluids::LinSys"))
           
           (goto-char (point-min))
           (while (re-search-forward "MATH_LINALG_SOLVER" end t ) 
             (replace-match "PHYSICS_FLUIDS_LINSYS"))
           (goto-char begin)))
     #+END_SRC

**** Insert ifdef clauses
     
     #+BEGIN_SRC emacs-lisp
       (defun afs-insert-ifdef (macro &optional add-else ifndef)
         "Insert C preprocessor conditional #ifdef MACRO. To add an else
         clause set ADD-ELSE to t. To invert the ifdef to #ifndef MACRO
          set ifndef to t."
         (interactive "sName of macro: ")
         (let* ((start (if (use-region-p) (region-beginning) (point-at-bol)))
                (end (if (use-region-p) (region-end) (point-at-eol)))
                (text (delete-and-extract-region start end))
                (defcmd (if ifndef "#ifndef" "#ifdef")))
           (insert (concat (format "%s %s\n%s\n" defcmd macro text)
                           (when add-else (format "#else\n%s\n" text))
                           "#endif"))
           ))
     #+END_SRC

     #+BEGIN_SRC emacs-lisp
       (defun afs-insert-ifdef-else (macro)
         "Insert C prepocessor conditional #ifdef MACRO with an else clause.
       Wrapper for (afs-insert-ifdef MACRO t)"
         (interactive "sName of macro: ")
         (afs-insert-ifdef macro t))
     #+END_SRC

     #+BEGIN_SRC emacs-lisp
       (defun afs-insert-ifndef (macro)
         "Insert C prepocessor conditional #ifndef MACRO."
         (interactive "sName of macro: ")
         (afs-insert-ifdef macro nil t))
     #+END_SRC

     #+BEGIN_SRC emacs-lisp
       (defun afs-insert-ifndef-else (macro)
         "Insert C prepocessor conditional #ifndef MACRO."
         (interactive "sName of macro: ")
         (afs-insert-ifdef macro t t))
     #+END_SRC

**** Convert java style comment to doxygen
    #+BEGIN_SRC emacs-lisp
      (defun convert-java-comment-to-doxygen ()
          "Convert java style comment to doxygen"
        (interactive)
        (let ((begin) (end))
          (if (use-region-p)
              (progn (setq begin (region-beginning) end (region-end)))
            (progn (setq begin (point) end nil)))
          (goto-char begin)
          (while (re-search-forward
                  "/\\*\\*\n[ ]+\\*\\(.*\\)\n[ ]+\\*/"
                  end t )
            (replace-match "///\\1"))))

    #+END_SRC 
** Workspace
   Function for splitting emacs into three frames. 
   Really nice to use with i3wm.
   #+BEGIN_SRC emacs-lisp
     (defun setup-home ()
     "Splits the session into three frames"
     (interactive)
     (delete-other-frames)
     (delete-other-windows)
     (make-frame-command)
     (make-frame-command))
   #+END_SRC
** Split lines
   Function for splitting lines at specified character. Default is ','.
   #+BEGIN_SRC emacs-lisp
     (defun split-at (&optional delim)
     "Split region/line at DELIM, if there are multiple matches it
     will split each one. DELIM will default to \",\" if no delim is
     given."
     (interactive "sSpecify delimiter: ")
     (when (or (string= delim "") (not delim)) (setq delim ","))
     (let ((start (if (use-region-p) (region-beginning) (point-at-bol)))
           (end (if (use-region-p) (region-end) (point-at-eol)))
           (regex delim))
       (goto-char start)
      
       (while (search-forward-regexp regex end t)
         (insert "\n")
         (setq end (1+ end)))
       (indent-region start end)
       (goto-char start)))

     (defun split-at-comma ()
     "wrapper for split-at for use with key command"
     (interactive)
     (split-at ","))
   #+END_SRC
** Yesterday-time
   Computes the time 24 hours ago
   #+BEGIN_SRC emacs-lisp
     (defun yesterday-time ()
     "Provide the date/time 24 hours before the time now in the format of current-time."
       (let* ((now-time (current-time))              ; get the time now
              (hi (car now-time))                    ; save off the high word
              (lo (car (cdr now-time)))              ; save off the low word
              (msecs (nth 2 now-time)))              ; save off the milliseconds

         (if (< lo 20864)                        ; if the low word is too small for subtracting
             (setq hi (- hi 2)  lo (+ lo 44672)) ; take 2 from the high word and add to the low
           (setq hi (- hi 1) lo (- lo 20864)))   ; else, add 86400 seconds (in two parts)

         (list hi lo msecs))) ; regurgitate the new values
   #+END_SRC
* Custom plugins
** Multiple cursor extension
   #+BEGIN_SRC emacs-lisp
     (use-package mc-extra-extra
       :ensure nil
       :load-path "~/emacs.d/plugins")
   #+END_SRC
* Custom keybindings
** Macros
    Macro to quickly open a file that is located on my machine at work.
    Inserts "fredriks@bcws649.d2vancouver.com:fredriks/swdevl/CoreLibs"
    Old machine was bcbellws108.
    #+BEGIN_SRC emacs-lisp
      (fset 'bcws
         [?b ?c ?w ?s ?4 ?2 ?7 ?. ?d ?2 ?v ?a ?n ?c ?o ?u ?v ?e ?r ?. ?c ?o ?m ?: ?f ?r ?e ?d ?r ?i ?k ?s ?/ ?s ?w ?d ?e ?v ?l ?/ ?C ?o ?r ?e ?L ?i ?b ?s])
    #+END_SRC

    And bind it to the key combo
    #+BEGIN_SRC emacs-lisp
      (global-set-key (kbd "C-c B") 'bcws)
    #+END_SRC
** Registers
   Quickly jump to files by pressing C-x r j <register>
   Jump to my init file with 'e' and init directory with 'i'.
   #+BEGIN_SRC emacs-lisp
     (set-register ?e (cons 'file "~/.emacs.d/init.el")) 
     (set-register ?i (cons 'file "~/.emacs.d/init.d/configuration.org")) 
   #+END_SRC
** UI
   Key bindings if I really need to see the menu and tool bar
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "<f5>") 'menu-bar-mode)
     (global-set-key (kbd "<f6>") 'tool-bar-mode)
   #+END_SRC
   
** Navigation
   Jump to specific line.
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "M-g") 'goto-line)
   #+END_SRC
   
   Open file at point.
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-x f") 'find-file-at-point)
   #+END_SRC
   
** Text search
   I'm using the regex variant of the text search more than the normal one.
   Swapping keybindings for them
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-M-s") 'isearch-forward)
     (global-set-key (kbd "C-M-r") 'isearch-backward)
     (global-set-key (kbd "C-s") 'isearch-forward-regexp)
     (global-set-key (kbd "C-r") 'isearch-backward-regexp)
     (global-set-key (kbd "C-S-s") 'isearch-forward-symbol-at-point)
   #+END_SRC
** Text edit
   Bind replace regexp to meta r
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "M-r") 'replace-regexp)
   #+END_SRC
   
   Duplicate line
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-c l") 'duplicate-line)
   #+END_SRC

   Split line at comma
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-,") 'split-at-comma)
   #+END_SRC
** Buffer functions
   Key bindings for revert-all-buffers and rename current buffer
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-c r") 'revert-all-buffers)
     (global-set-key (kbd "C-c R") 'rename-current-file-or-buffer)
   #+END_SRC
** C Common
   Hide/Show code blocks
   #+BEGIN_SRC emacs-lisp
     (add-hook 'c-mode-common-hook
       (lambda()
         (local-set-key (kbd "C-c <right>") 'hs-show-block)
         (local-set-key (kbd "C-c <left>")  'hs-hide-block)
         (local-set-key (kbd "C-c <up>")    'hs-hide-all)
         (local-set-key (kbd "C-c <down>")  'hs-show-all)
         (hs-minor-mode t)))
   #+END_SRC

   When in a c family buffer use shift tab to switch between header
   and source
   #+BEGIN_SRC emacs-lisp
     (add-hook 'c-mode-common-hook
       (lambda() 
         (local-set-key  (kbd "<backtab>") 'ff-find-other-file)))
   #+END_SRC
** Compile
   Key bindings to run make on current location and to re-run the
   command.
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "<f12>") 'compile)
     (global-set-key (kbd "<f11>") 'recompile)
   #+END_SRC
** Subversion
   Key bindings for the custom subversion commands
   #+BEGIN_SRC emacs-lisp
     (global-set-key (kbd "C-c s u") 'svn-url)
     (global-set-key (kbd "C-c s r") 'svn-repo-url)
     (global-set-key (kbd "C-c s t") 'svn-trunk-url)
     (global-set-key (kbd "C-c s T") 'svn-tag-url)
     (global-set-key (kbd "C-c s b") 'svn-branch-url)
     (global-set-key (kbd "C-c s R") 'svn-root-url)
   #+END_SRC
* Bug workarounds
  Workarounds for bugs I have encountered through out the years
** Cursor turns black
   Set the cursor color to white.
   #+BEGIN_SRC emacs-lisp
     (set-cursor-color "#ffffff")
   #+END_SRC
** Maximize emacs under KDE
   Issue maximizing emacs with KDE at work
   #+BEGIN_SRC emacs-lisp
     (setq frame-resize-pixelwise t)
   #+END_SRC
** Juniper VPN linux 4.5+
   Juniper VPN doesn't work in linux 4.5+, workaround is to disable
   the ipv6.
   #+BEGIN_SRC sh :tangle no
   echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6   
   #+END_SRC
** Tramp hangs after password entry 
   :PROPERTIES:
   :CUSTOM_ID:  tramp-hang-workaround 
   :END:
   See [[https://www.emacswiki.org/emacs/TrampMode#toc7][EmacsWiki]]
   Simple fix if you don't want to use emacs shells is to add this to your .zshrc
   #+BEGIN_SRC sh :tangle no
     [[ $TERM == "dumb" ]] && unsetopt zle && PS1='$ ' && return
   #+END_SRC

   Problem with this though it that it messes up with the prompt when
   running a emacs shell. For that use:
   #+BEGIN_SRC sh :tangle no
     # Tramp and emacs shell workaround
     if [[ $TERM == "dumb" ]]
     then
         # Emacs shell/tramp cannot handle line editing, turning it off.
         unsetopt zle

         # The custom prompt will hang tramp.
         # Change to something simpler and stop
         if [[ $INSIDE_EMACS == '' ]]
         then
             PS1='$ '
             return
         fi
     fi
   #+END_SRC

   Similar issue will happen with a bash shell on the other end. And
   for that you can just remove the =unsetopt zle=.
   
   The [[https://www.gnu.org/software/emacs/manual/html_node/tramp/Remote-shell-setup.html][manual]] describe that you can customize the
   =tramp-shell-prompt-pattern= to match your remote prompt. Didn't
   not get that to work. Same with the =Interactive shell prompt= from
   what I can tell tramp doesn't set INSIDE_EMACS to contain tramp. So
   this is the only workaround I found that is working. I.e. tramp
   sets the terminal to dumb when testing a connection but it doesn't
   set INSIDE_EMACS. Those two are set when running a shell either
   locally or remote. When using a tramp connection it sets the
   HISTFILE to be a tramp file. That's the only way I found to
   distinguish between a shell that is running locally or from a tramp
   connection.

* Notes
** Lisp in search replace
   To execute a lisp function in replace regexp do \,(<function>)
** Skip code block
   You can use =:tangle no= in the =SRC_BLOCK= to ignore the code
   block from being exported aka tangled. Good for example blocks that
   you don't want to end up in you config file.
** Flycheck
*** Tweak flycheck
   To set specific compiler and flags for a specific project you can
   use something like this in a .dir-locals.el file:
   #+BEGIN_SRC emacs-lisp :tangle no
     ;; File .dir-locals.el
     ( ( c++-mode 
         . ((flycheck-c/c++-gcc-executable . "/tools/package/gcc/6.4.0/bin/g++" )
            (flycheck-gcc-language-standard . "c++14")
            (flycheck-gcc-include-path
             . ("/dd/dept/software/users/fredriks/swdevl/corelibs/PRIVATE/include") )
            (flycheck-gcc-includes . ("openvdb/math/Vec3.h"))
            (flycheck-gcc-warnings . ("all"))
            (flycheck-gcc-definitions
             . ("_GLIBCXX_USE_CXX11_ABI=0"
                "EIGEN_MATRIXBASE_PLUGIN=<DD/Utility/EigenMatrixBaseAddon.hpp>"
                "DD_OPEN_MESH_POLYMESHT_EXTENSION=<DD/Math/Geometry/OpenMesh/OpenMesh_PolyMeshT_Extension.hpp>"
                "DD_OPEN_MESH_TRIMESHT_EXTENSION=<DD/Math/Geometry/OpenMesh/OpenMesh_TriMeshT_Extension.hpp>"
                "DD_CORELIBS_USE_OPENMESH"
                "DD_CORELIBS_BUILD_LIBS"
                "EIGEN_MATRIXBASE_PLUGIN=<DD/Utility/EigenMatrixBaseAddon.hpp>"
                "EIGEN_MATRIX_PLUGIN=<DD/Utility/EigenMatrixAddon.hpp>"
                ))
            (flycheck-gcc-args 
             . ("-B/tools/package/binutils/2.29.1/bin"
                "-isystem/tools/package/openvdb/4.0.1_dd01/include"
                "-isystem/tools/package/eigen/3.3.4/include/eigen3"
                "-isystem/tools/package/embree/2.15.1_gcc4.8/include"
                "-isystem/tools/package/gtest/1.8.0/include"
                "-isystem/tools/package/openmesh/6.3/include"
                "-isystem/tools/package/tbb/4.4.6/include"
                "-isystem/tools/package/boost/1.61.0/include"
                "-isystem/tools/package/blosc/1.5.0/include"
                "-isystem/tools/package/ilmbase/2.2.0/include/Ilmbase"
                "-isystem/tools/package/ilmbase/2.2.0/include"
                "-isystem/tools/package/ilmbase/2.2.0/include/OpenEXR"
                "-isystem/tools/package/corelog/3.0.2/include"
                "-isystem/tools/package/qhull/2012.1/include"
                "-isystem/tools/include"
                )))))
   #+END_SRC
   For clang just replace gcc with clang.

   If you want to play it more safe you can use the flychecks other
   variables (see C-c ! ?). Note that flycheck-include-path just
   prepend -I for all strings in the list. So for third party libs
   it's better to use -isystem.

   Also prefer flycheck-gcc-includes over adding that in
   flycheck-gcc-args as if you do
   #+BEGIN_SRC emacs-lisp :tangle no
     (flycheck-gcc-args 
      . ("-include openvdb/math/Vec3.h")
     )
   #+END_SRC
   You'll get an error about cannot find file, even though the file
   actually exist. That's because the thing that parses this and
   passes it to a shell escapes the whitespace after -include. So for
   that to work you'll need to do:

   #+BEGIN_SRC emacs-lisp :tangle no
     (flycheck-gcc-args 
      . ("-includeopenvdb/math/Vec3.h")
     )
   #+END_SRC
   Which is not that readable.

*** Language standard in c++
   Specify language standard in dir locals file: .dir-locals.el 
   For example
   ((c++-mode
     (flycheck-clang-language-standard . "c++14")
     (flycheck-gcc-language-standard . "c++14")))
** Links
*** Elisp Regex
    Link to elisp regular expression
    https://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html
** Change font size on the fly
   Use commands
   C-x C-+ and C-x C--
** Git
*** Change message in most recent commit
    git commit --amend [-m ""]
** Github
*** Preview site of a git hosted website
    Prepend to the original url.
    #+BEGIN_SRC org :tangle no
      http://htmlpreview.github.io/?
    #+END_SRC
    For example to see an older page of the embree docs.
    #+BEGIN_SRC org :tangle no
      https://htmlpreview.github.io/?https://raw.githubusercontent.com/embree/embree.github.com/v2.15.0/index.html
    #+END_SRC
    source: [[https://stackoverflow.com/questions/8446218/how-to-see-an-html-page-on-github-as-a-normal-rendered-html-page-to-see-preview][stackoverflow]]
** Subversion
*** Roll back a tag

    Check out the tags directory. Use --depth=empty to avoid
    populating all the tags as this can take a really long time
    depending on how many tags exist.
    #+BEGIN_SRC sh :tangle no
      svn checkout SVN_URL/REPO/tags  --depth=empty REPO-tag-fix
    #+END_SRC
    
    Locate the revision to roll back to.
    #+BEGIN_SRC sh :tangle no
      svn log SVN_URL/REPO/tags
    #+END_SRC
    
    Then cd into the working copy and update all tags involved in the
    roll back. Otherwise svn will just ignore the roll back.
    #+BEGIN_SRC sh :tangle no
      cd REPO-tag-fix
      svn up TAG0 TAG1...
    #+END_SRC
    
    Roll back to the revision you want by simply merging the tags
    directory backwards to that revision.
    #+BEGIN_SRC sh :tangle no
      svn merge -rHEAD:REVISION .
    #+END_SRC

    Where REVISION is the revision number you picked previously. HEAD
    is a svn built in keyword and points to the latest revision.
    
** Org mode
   Create source block type "<s" on a new line and press <tab>
** Elisp
   Use C-h f to get docs on function
** Code
*** Generate a list of all defined macros
    cpp -dM /dev/null
**** Check what __cplusplus is set to when setting a language standard in c++
     Need to tell cpp that we only are interested in c++ then we can
     just pass the flags we want.

     For example check what __cplusplus is set to when using c++14.
     #+BEGIN_SRC sh
       cpp -dM -x c++ -std=c++14 /dev/null | grep __cplusplus
     #+END_SRC
*** Trace undefined symbol
    use ld's --trace-symbol=<symbol> when linking to get a list of
    what file(s) are using that symbol. Using it with gcc it would be
    #+BEGIN_SRC sh
      gcc <options> -Wl,--trace-symbols=<symbol>
    #+END_SRC
*** Run functions when loading/unloading shared libraries
    Call function when shared library is loaded, with gcc use:
    #+BEGIN_SRC c++
      __attribute__((constructor)) void func(){}
    #+END_SRC
    
    Call function when shared lbirary is unloaded, with gcc use:
    #+BEGIN_SRC c++
      __attribute__((destructor)) void func(){}
    #+END_SRC
    
** Ledger
*** Check what you spend on X
   #+BEGIN_SRC sh
     ledger -f data.dat reg payee "X" -s
   #+END_SRC
*** Scripts
    #+BEGIN_SRC sh
      env LEDGER_FILE=data.dat scripts/cashflow.sh
    #+END_SRC
** Find
*** Ignore directories while searching
    For example while searching for file named foobar, ignore all .svn
    directories.
    #+BEGIN_SRC sh
      find . -not \( -path '*/.svn' -prune \) -name "foobar"
    #+END_SRC
** Case-sensitive search
   press M-c after search

** ssh
*** ssh agent
    Use the ssh agent to cache the private key to a terminal
    #+BEGIN_SRC sh
      eval $(ssh-agent)
      ssh-add ~/.ssh/private-key
    #+END_SRC
** houdini
*** Expression for string parameters
    Create a keyframe (Alt+LMB or "Channels and keyframes" -> "set Keyframe")
    Then edit the expression.
** KDE
*** no borders
    When disabled use ALT+F3 to bring the menu back.
** Install fonts local to user
   Install fonts to ~/.fonts then update the fontconfig cache by
   running.
   #+BEGIN_SRC sh
     fc-cache -v ~/.fonts   
   #+END_SRC
   The option '-v' is just for verbose output and can be skipped.

   To see what fonts are installed run
   #+BEGIN_SRC sh
     fc-list
   #+END_SRC
** Remove/Keep lines matching regexp
   use 'keep-lines' to keep lines matching regexp.
   use 'flush-lines' to remove lines matching regexp.
** Terminfo files (ti)
   To compile FILE run
   #+BEGIN_SRC sh :tangle no
     tic FILE
   #+END_SRC
** Shell
   Stop the shell from echoing the command.
   #+BEGIN_SRC sh :tangle no
     stty -echo
   #+END_SRC
** CMake
   Don't remove the rpath when installing.
   #+BEGIN_SRC sh :tangle no
     CMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE
   #+END_SRC
   
   Specify c++ compiler.
   #+BEGIN_SRC sh :tangle no
     CMAKE_CXX_COMPILER=$(GCC_PACKAGE_ROOT)/bin/g++
   #+END_SRC
** Yum
   Find what package a file belongs to:
   #+BEGIN_SRC sh :tangle no
     yum whatprovides /path/to/file
   #+END_SRC
** rpm
   Find what package a file belongs to:
   #+BEGIN_SRC sh :tangle no
     rpm -qf /path/to/file
   #+END_SRC
